<template>
  <div class="main">
    <el-card class="box-card">
      <div class="card-header">
        <img class="platform-logo" src="@/assets/imgs/reading.png" />
        <div class="platform-info">
          <h1 class="platform-name">阅读创作平台</h1>
          <p class="platform-slogan">开启您的数字阅读之旅</p>
        </div>
      </div>

      <!-- 邮箱输入 -->
      <div class="custom-input-wrapper">
        <input
          v-model="loginForm.mail"
          class="custom-input"
          :class="{ 'invalid-input': !isEmailValid }"
          type="email"
          placeholder="请输入注册邮箱"
          @input="validations.email"
          @blur="validations.email"
        />
      </div>
      <div v-if="!isEmailValid" class="error-tip">请输入有效的邮箱地址</div>

      <!-- 密码输入 -->
      <div class="custom-input-wrapper">
        <input
          v-model="loginForm.password"
          class="custom-input"
          :class="{ 'invalid-input': !isPasswordValid }"
          type="password"
          placeholder="请输入密码"
          @input="validations.password"
          @blur="validations.password"
        />
      </div>
      <div v-if="!isPasswordValid" class="error-tip">
        密码需包含字母和数字（6-20位）
      </div>

      <div class="verify-code-container">
        <div class="code-input-wrapper">
          <input
            v-model="codeInput"
            class="code-input"
            type="text"
            placeholder="验证码"
            maxlength="4"
            :class="{ 'invalid-input': codeInput.length < 4 }"
          />
          <div v-if="codeInput.length < 4" class="error-tip">
            请输入4位验证码
          </div>
        </div>

        <div class="code-display" @click="fetchVerifyCode">
          <span id="verify-code" class="distorted-text">{{ verifyCode }}</span>
          <el-icon class="refresh-icon"><Refresh /></el-icon>
        </div>
      </div>

      <!-- 登录按钮 -->
      <!-- 修改按钮组结构 -->
      <div class="auth-buttons">
        <el-button
          class="button"
          type="primary"
          size="large"
          @click="handleLogin"
          >登录</el-button
        >

        <el-button type="primary" size="large" @click="register"
          >注册</el-button
        >
      </div>

      <el-alert
        v-if="msg"
        :title="msg"
        type="error"
        show-icon
        class="alert-message"
      />
    </el-card>
  </div>
</template>
<script setup>
import { useRouter } from 'vue-router'
import { onMounted, ref, nextTick, computed } from 'vue'
import { login, getVerifyCode } from '@/apis/login'
import { useAccountStore } from '@/stores/useAccountStore.js'

const router = useRouter()
const accountStore = useAccountStore()

// 状态定义
const verifyCode = ref('')
const sessionId = ref('')
const codeInput = ref('')
const agree = ref(1)
const msg = ref('')

// 登录表单数据
const loginForm = ref({
  mail: '',
  password: '',
  code: '',
  sessionId: '',
})

// 验证状态
const isEmailValid = ref(true)
const isPasswordValid = ref(true)

// 邮箱验证正则
const EMAIL_REGEX = /^[^\s@]+@(gmail|qq|163|outlook|hotmail)\.com$/
// 密码验证正则（至少包含字母和数字，6-20位）
const PASSWORD_REGEX = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,20}$/

// 实时验证函数
const validations = {
  email: () => {
    isEmailValid.value = EMAIL_REGEX.test(loginForm.value.mail)
  },
  password: () => {
    isPasswordValid.value = PASSWORD_REGEX.test(loginForm.value.password)
  },
}

// 表单有效性计算
const isFormValid = computed(() => {
  return (
    isEmailValid.value &&
    isPasswordValid.value &&
    codeInput.value.length === 4 && // 假设验证码为4位
    agree.value === 1
  )
})

// 登录逻辑
const handleLogin = async () => {
  // 新增性别验证

  if (!isFormValid.value) {
    msg.value = '请检查输入内容是否符合要求'
    return
  }

  try {
    const res = await login({
      ...loginForm.value,
      code: codeInput.value,
      sessionId: sessionId.value,
    })

    if (res.code === '200') {
      accountStore.setAccount({
        uid: res.data.uid,
        token: res.data.token,
        type: res.data.type,
        username: res.data.username,
      })
      router.push('/loading')
    } else {
      msg.value = res.message || '登录失败，请检查账号和密码'
    }
  } catch (error) {
    console.error('登录失败:', error)
    msg.value = '服务器异常，请稍后重试'
  }
}
const register = () => {
  router.push({
    path: '/register',
  })
}
// 星评值
const value = ref(5)

// 获取验证码
const fetchVerifyCode = async () => {
  try {
    const res = await getVerifyCode()
    if (res.code === '200') {
      verifyCode.value = res.data.verifyCode
      sessionId.value = res.data.sessionId
      applyCodeEffect() // 应用干扰效果
    }
  } catch (error) {
    console.error('获取验证码失败:', error)
  }
}

// 应用验证码干扰效果
const applyCodeEffect = () => {
  nextTick(() => {
    const codeElement = document.getElementById('verify-code')
    if (codeElement) {
      codeElement.style.transform = `rotate(${Math.random() * 10 - 5}deg)`
      codeElement.style.filter = `hue-rotate(${Math.random() * 360}deg)`
      codeElement.style.letterSpacing = `${Math.random() * 5}px`
    }
  })
}

onMounted(() => {
  fetchVerifyCode()
})
</script>
<style scoped>
.main {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 90vh;
  background: url('@/assets/imgs/backgroud.jpg') no-repeat center center fixed;
  background-size: cover;
  margin: 0;
}

.box-card {
  width: 450px; /* 限制卡片的最大宽度 */
  background-color: rgba(255, 255, 255, 0.8);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.input {
  margin-top: 25px;
  height: 38px;
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: center;
  align-items: center;
}

.verify-code-container {
  display: flex;
  gap: 10px;
  margin-top: 25px;
}

.verify-code-container {
  display: flex;
  gap: 10px;
  margin-top: 25px;
}

.code-input-wrapper {
  flex: 1;
  position: relative;
}

.code-input {
  width: 100%;
  height: 38px;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.code-input:focus {
  border-color: #409eff;
  outline: none;
}

/* 调整验证码显示区域 */
.code-display {
  width: 120px;
  height: 38px;
  background: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  position: relative;
  flex-shrink: 0;
}

.distorted-text {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  transition: all 0.3s;
  transform-origin: center;
  position: relative;
  z-index: 1;
}

.refresh-icon {
  position: absolute;
  right: 5px;
  bottom: 5px;
  color: #909399;
  font-size: 14px;
}

/* 新增样式 */
.custom-input-wrapper {
  margin-top: 25px;
}

.custom-input {
  width: 100%;
  padding: 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.custom-input:focus {
  border-color: #409eff;
  outline: none;
}

.invalid-input {
  border-color: #f56c6c;
}

.error-tip {
  color: #f56c6c;
  font-size: 12px;
  margin: 4px 0;
  height: 20px;
}
/* 新增头部样式 */
.card-header {
  display: flex;
  align-items: center;
  justify-content: flex-start; /* 左对齐 */
  gap: 15px; /* 元素间距 */
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 25px;
}

.platform-logo {
  height: 60px;
  width: 60px;
  object-fit: contain;
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
}

.platform-info {
  display: flex;
  flex-direction: column;
}

.platform-name {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
  letter-spacing: 1px;
  background: linear-gradient(135deg, #409eff 30%, #2c3e50 70%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.platform-slogan {
  margin: 4px 0 0;
  font-size: 14px;
  color: #909399;
  font-style: italic;
}

/* 调整卡片宽度 */
.box-card {
  width: 480px;
  border-radius: 12px;
  overflow: hidden;
}

/* 调整输入框上方间距 */
.custom-input-wrapper {
  margin-top: 20px;
}
/* 新增按钮组样式 */
.auth-buttons {
  display: flex;
  justify-content: center;
  gap: 20px; /* 控制按钮间距 */
  margin-top: 50px;
}

/* 调整警告信息样式 */
.alert-message {
  margin-top: 20px;
}
</style>
